<style scoped lang="scss" rel="stylesheet/scss">
    @import '~@/scss/global/colors.scss';

    $color-w: rgba($sidebar-txt, 1);
    $color-w2: rgba($sidebar-txt, .6);
    $color-bgHover: darken($sidebar-bg, 3%);
    $color-split: rgba($sidebar-txt, .08);
    $sidebar-w: 210px;
    $sidebar-h: 43px;
    $sidebar-fold: 42px;


    .ui-sidebar {
        @media screen and (max-width: 1366px) {
            .Sidebar {
                width: $sidebar-fold;

                &:hover {
                    width: $sidebar-w;
                }

                > .content {
                    padding: 0 !important;
                }
            }
            .Sidebar-toggle {
                display: none;
            }

        }
    }


    .Sidebar-toggle {
        position: absolute;
        width: 100%;
        height: 30px;
        top: 0;
        right: 0;
        z-index: 10;

        > div {
            width: 100%;
            height: 30px;
            background: $sidebar-toggle-bg;
            z-index: 100;
            cursor: pointer;
            box-shadow: $sidebar-toggle-shadow;
            color: $sidebar-toggle-txt;

            > i {
                position: relative;
                left: 2px;
                bottom: 2px;
            }
        }

        &:hover {
            > div {
                visibility: visible;
            }

            > div:hover {
                visibility: visible;
                color: $sidebar-toggle-txt-hover;
            }
        }
    }

    .Sidebar {
        > .content {
            padding: 30px 0 0 0;
        }

        &.hide {
            width: $sidebar-fold;
        }

        overflow: hidden;
        width: $sidebar-w;

        @keyframes c1-leftin {
            from {
                left: -$sidebar-w;
            }

            to {
                left: 0;
                display: none;
            }
        }

        @keyframes c1-rightin {
            from {
                right: -$sidebar-w;
            }

            to {
                right: 0;
                display: none;
            }
        }

        @keyframes c2-leftout {
            from {
                left: 0;
            }

            to {
                left: -$sidebar-w;
                display: none;
            }
        }

        @keyframes c2-rightout {
            from {
                right: 0;
            }

            to {
                right: -$sidebar-w;
                display: none;
            }
        }

        .c1-left,
        .c1-right,
        .c2-left,
        .c2-right {
            animation-duration: .2s;
            animation-fill-mode: both;
        }

        .c1-left {
            animation-name: c1-leftin;
        }

        .c1-right {
            animation-name: c1-rightin;
        }

        .c2-left {
            animation-name: c2-rightout;
        }

        .c2-right {
            animation-name: c2-leftout;
        }

        .cont1,
        .cont2 {
            background: $sidebar-bg;
        }

        .cont2 {
            display: none !important;
            margin-top: 0;
        }

        .show {
            display: block !important;
            z-index: 9;
        }

        .topbar {
            background: $sidebar-topbar;
            position: relative;
            z-index: 2;
            padding: 12px 10px;
            box-shadow: $sidebar-topbar-shadow;
            /*cursor: pointer;*/

            a {
                color: $color-w2;
            }

            & {

                a:hover,
                i:hover {
                    color: $sidebar-topbar-hover;
                    cursor: pointer;
                }
            }
        }

        .menulist {
            height: $sidebar-h;
            position: relative;
            overflow: hidden;
            white-space: nowrap;

            .quanquan {
                width: 20px;
                height: 20px;
                border-radius: 50%;
                background: rgba($sidebar-txt, .7);
                color: $sidebar-bg;
                display: inline-block;
                font-size: 12px;

                &::before {
                    position: relative;
                    top: 0;
                }
            }

            .placeholder {
                width: 20px;
                height: 20px;
                margin-right: 10px;
                display: inline-block;
                background: rgba($sidebar-txt, .7);
                position: relative;
                border-radius: 50%;
                text-align: center;
                text-transform: uppercase;
                font-weight: bold;

                &::before {
                    position: relative;
                    top: 0;
                    content: attr(text);
                    color: $sidebar-bg;
                }
            }

            .splitLine {
                display: block;
                height: 0;
                border-bottom: $sidebar-splitLine;
            }

            &.fold {
                width: $sidebar-fold;
            }

            &:last-child {
                border: none;
            }

            .right.icon {
                float: right;
            }

            &:hover {
                width: auto;
                cursor: pointer;
                background: $color-bgHover;

                > a,
                > div {
                    display: inline-block;
                    color: $color-w;
                }
            }

            &.active {
                background: $sidebar-heightLight;

                > a,
                > div {
                    color: $sidebar-active;
                }

                .quanquan,
                .placeholder {
                    background: $sidebar-active-icon;
                }
            }

            &.active:hover {
                cursor: pointer;
                background: $sidebar-heightLight;
            }

            &.factive::before {
                content: "";
                position: absolute;
                width: 3px;
                height: 100%;
                background: $sidebar-heightLight;
            }

            > a > i,
            > div > i {
                margin-right: 10px;
            }

            > div {
                width: $sidebar-w;
            }

            > a,
            > div {
                min-width: 209px;
                font-size: 13px;
                color: $color-w2;
                display: block;
                padding: 12px 10px;
            }

            &:not(.fold) {
                > a.RockAndRoll {
                    position: absolute;
                    left: 0;
                    top: 0;
                    min-width: 100%;

                    &:hover {
                        animation: hoverShowAll 2s linear .5s infinite alternate;
                    }

                    @keyframes hoverShowAll {
                        from {
                            transform: translate3d(0, 0, 0);
                        }

                        to {
                            transform: translate3d(-30%, 0, 0);
                        }
                    }
                }
            }
        }
    }

    .title-box {
        display: flex;
        position: relative;
        font-size: 16px;
        justify-content: space-between;

        .title-box-left {
            overflow: hidden;
            white-space: nowrap;
        }
    }

    .col-search {
        position: absolute;
        right: 0;
        top: -9px;
        color: rgba(255, 255, 255, 0.6);
        background-color: #1d2936;
        margin-right: 0;
        padding: 9px 0 9px 9px;
        box-sizing: content-box;
    }

    .search-box {
        position: absolute;
        top: 6.5px;
        left: 10px;
        width: 190px;
        height: 30px;
        opacity: 1;
        background-color: #1d2936;
        overflow: hidden;

        .search-input {
            box-sizing: border-box;
            height: 100%;
            width: 100%;
            border: none;
            background-color: transparent;
            border-bottom: 1px solid rgba(#fff, .4);
            padding: 0 25px;
            color: rgba(255, 255, 255, 0.8);
            outline: none;
        }

        .search-icon {
            position: absolute;
            left: 5px;
            line-height: 32px;
            color: rgba(255, 255, 255, 0.8);
        }
    }

    .search-enter, .search-leave-active {
        width: 0;
        left: 200px;
        opacity: .2;
    }

    .search-enter-active, .search-leave-active {
        transition: width .1s ease-in-out, left .1s ease-in-out, opacity .1s;
    }
</style>
<template>
    <div class="ui flex item ui-sidebar" v-if="noLogin">
        <!--<div v-if="dimmer" style="position:absolute; width:100%; height:100%; z-index:1">
            <div class="ui active dimmer"
                style="background:rgba(54, 65, 80, .7); border:none">
                <div class="ui text loader"></div>
            </div>
        </div>-->
        <div class="Sidebar-toggle" v-show="received" :style="dimmer ? 'width:0' : ''">
            <div @click="toggle()" class="ui flex row-center col-center">
                <i class="icon" :class="[toggleVal ? 'bars':'ellipsis vertical']"></i>
            </div>
        </div>
        <div class="Sidebar ui flex item" :class="{hide:toggleVal}" :style="dimmer ? 'width:0' : ''">
            <div ref="cont1" class="ui flex column content" :class="cont1" v-if="received">
                <div class="topbar" v-if="parentState.title">
                    <div class="title-box">
                        <a class="title-box-left" @click="goTo('back')">
                            <i class="icon caret left"></i>
                            <strong v-if="!toggleVal">{{parentState.title}}</strong>
                        </a>
                        <i class="icon search col-search"
                            v-show="!showSearch && !toggleVal && searchBar && menuData.length > 10"
                            @click.stop="showInput"></i>
                    </div>
                    <transition name="search">
                        <div class="search-box" v-show="showSearch" @click.stop>
                            <input type="text"
                                class="search-input"
                                @blur="hideInput"
                                @keyup.esc='resetInput'
                                v-model.trim="searchText"
                                ref="searchInput">
                            <i class="icon search search-icon"></i>
                        </div>
                    </transition>
                </div>
                <ui-scrollbar class="ui item one">
                    <el-tooltip :disabled="!toggleVal"
                        class="item"
                        v-for="item in (searchText ? searchArr : menuData)"
                        :key="item.state"
                        effect="dark"
                        :content="item.title"
                        placement="right"
                        :open-delay="200">
                        <div class="menulist"
                            :class="{active : item.state === currentState, fold:toggleVal, factive:item.state === curParent}">
                            <a @click="linkTo('/'+item.state.trim())" v-if="!hasChildren(item)" @mouseover="getMov">
                                <i class="quanquan" v-if="item.icon && item.icon.length > 1" :class="item.icon"></i>
                                <span class="placeholder" v-else-if="item.icon && item.icon.length === 1" :text="item.icon.trim()"></span>
                                <span v-else class="placeholder" :text="item.title.trim().substr(0, 1)"></span>
                                {{item.title}}
                            </a>
                            <div v-if="hasChildren(item)" @click="goTo('sub', item.state)" @mouseover="getMov">
                                <i class="quanquan" v-if="item.icon && item.icon > 1" :class="item.icon"></i>
                                <span class="placeholder" v-else-if="item.icon && item.icon.length === 1" :text="item.icon.trim()"></span>
                                <span v-else class="placeholder" :text="item.title.trim().substr(0, 1)"></span>
                                <i class="caret right icon"></i>
                                {{item.title}}
                            </div>
                            <span class="splitLine" v-if="+item.splitLine > 0"></span>
                        </div>
                    </el-tooltip>
                    <div v-if="searchText && searchArr.length === 0" class="menulist" @click="searchText = ''">
                        <a class="t-c">
                            暂无数据,点击重置
                        </a>
                    </div>
                </ui-scrollbar>
            </div>
            <div ref="cont2" class="ui flex column content" :class="cont2">
                <div class="topbar" v-if="menuCache.parentState.title">
                    <div style="font-size:16px">
                        <a>
                            <i class="icon caret left"></i>
                            <strong>{{menuCache.parentState.title}}</strong>
                        </a>
                    </div>
                </div>
                <div class="ui item one scrollbar scroll-dark">
                    <div class="menulist"
                        v-for="(item, index) in menuCache.data"
                        :class="{active : item.state === currentState}"
                        :key="index">
                        <a v-if="typeof item.subMenu === 'undefined'">
                            <i v-if="item.icon" :class="item.icon"></i>
                            {{item.title}}
                        </a>
                        <div v-if="typeof item.subMenu !== 'undefined'">
                            <i v-if="item.icon" :class="item.icon"></i>
                            <i class="caret right icon"></i>
                            <span>{{item.title}}</span>
                        </div>
                        <span class="splitLine" v-if="+item.splitLine > 0"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
    export default {
        name: 'ui-sidebar-b',
        props: {
            searchBar: {
                type: Boolean,
                default: true
            },
            sort: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                dimmer: true,
                showSearch: false, // 是否弹出搜索框
                searchText: '', // 搜索内容
                searchArr: [], // 搜索出来的数据
                rawData: '', //原始数据
                menuData: '', //临时数据1
                toggleVal: false, //侧栏折叠控制
                parentState: { //目录的父级名称
                    title: null,
                    state: null
                },
                menuCache: { //临时数据2
                    data: '',
                    parentState: {
                        title: null,
                        state: null
                    }
                },
                received: false, //异步接收数据完成改变值为ture
                currentState: '', //当前路由的state值
                cont1: '', //内容区域1 class 变量
                cont2: 'cont2', //内容区域2 class 变量
                curParent: ''
            }
        },
        mounted() {
            //this.log(this.searchBar)
            //首次进入调取侧栏折叠状态
            if (window.localStorage.getItem('showsSideBar') !== null) {
                this.toggleVal = true;
            }
            //首次进入
            this.routeData(this.$route)

        },
        watch: {
            //监听路由变化后执行动作
            '$route'(to, from) {
                this.routeData(to, from)
            },
            searchText(newValue, oldValue) {
                let str = newValue.toLowerCase()
                this.searchArr = this.menuData.filter((item) => {
                    let pinyinCode = item.pinyin_code || item.pinyinCode;
                    if (pinyinCode) {
                        return item.title.toLowerCase().includes(str) || pinyinCode.includes(str)
                    }else{
                        return item.title.toLowerCase().includes(str)
                    }
                })
            }
        },
        computed: {
            noLogin() {
                let path = this.$route.fullPath
                return path !== '/loginFed' && path !== '/login' && path !== '/welcome'
            }
        },
        methods: {
            //鼠标移动上去如果文字太长就滚动
            getMov(e) {
                // console.log(e.target.clientWidth, e.target.className.length);
                if (e.target.clientWidth > 210 && e.target.className.length < 1) {
                    e.target.className = 'RockAndRoll'
                }
            },
            hasChildren(item) {
                return (item.hasChildren === 'true' || item.hasChildren === true)
            },
            //展开折叠侧栏方法
            toggle() {
                //存储当前展开关闭状态让刷新后能保持住 (存储状态貌似没什么卵用了)
                let storage = window.localStorage;
                this.toggleVal = !this.toggleVal;
                if (storage.getItem('showsSideBar') !== null) {
                    storage.removeItem('showsSideBar')
                }else{
                    storage.setItem('showsSideBar', '')
                }

                // 告诉echart需要重绘
                this.$eventHub.$emit('echartResize', true)
            },
            //加载数据方法
            routeData(to) {

                // 在登录的时候就什么都不要做
                if (!this.noLogin) {
                    return false
                }

                this.$nextTick(() => {

                    if (!to.matched[0]) return

                    //获取当前路由路径值
                    let _path = to.matched[0].path.replace('/', '');

                    //清理动画css
                    let clearAnimat = () => {
                        let _run = () => {
                            this.cont1 = 'cont1';
                            this.cont2 = 'cont2';
                        };
                        this.$refs['cont2'].addEventListener('animationend', _run);
                    };

                    if (this.received) { //如果获取远程数据过就直接执行
                        this.goTo('to', _path);
                        clearAnimat();
                    }else{ //如果没有获取过远程数据,就去远程调用数据然后再执行
                        let sidebarData = this.$store.getters.sidebar;
                        if (sidebarData) {
                            this.rawData = sidebarData;
                            // 按拼音首字母排序
                            if (this.sort) {
                                this.sortArr(this.rawData, 'title')
                            }
                            this.menuData = sidebarData;
                            this.received = true;
                            //数据加载成功执行打开对应栏目方法
                            this.goTo('to', _path);
                            clearAnimat();
                            this.dimmer = false;
                        }
                    }

                })

            },

            //加载对应栏目并点亮对应栏目方法
            goTo(dist, item) {
                //一个递归
                let _getNodesObj = {};
                let getNodes = function(data, state, out, n) {

                    for (let i = 0, len = data.length; i < len; i++) {
                        let node = data[i];
                        // console.log(data, state)
                        if (node.state.trim() === state.trim()) {
                            out.length = n + 1;
                            out[n] = node;
                            return true;
                        }
                        if (node.subMenu) {
                            if (getNodes(node.subMenu, state, out, n + 1)) {
                                out[n] = node;
                                return true;
                            }
                        }
                    }
                    return false;
                };
                //执行缓存
                this.menuCache.data = this.menuData; //存储上一次目录数据
                this.menuCache.parentState.title = this.parentState.title; //存储上一次顶部按钮数据
                this.menuCache.parentState.state = this.parentState.state; //存储上一次顶部按钮数据

                //点击下一级打开的菜单
                if (dist === 'sub') {
                    //执行动画
                    this.cont1 = 'cont1 c1-right';
                    this.cont2 = 'cont2 show c2-right';

                    getNodes(this.rawData, item, _getNodesObj, 0);
                    let obj;
                    if (_getNodesObj.length > 1) {
                        obj = _getNodesObj[_getNodesObj.length - 1];
                        this.menuData = obj.subMenu;
                        this.parentState.title = obj.title;
                        this.parentState.state = obj.state;
                        // console.log(obj.subMenu)
                    }else{
                        obj = _getNodesObj[0];
                        this.menuData = obj.subMenu;
                        this.parentState.title = obj.title;
                        this.parentState.state = obj.state;
                        this.menuCache.parentState.title = null;
                        this.menuCache.parentState.state = null;

                        // 按拼音首字母排序
                        if (this.sort) {
                            this.sortArr(this.menuData, 'title')
                        }

                    }
                }
                //通过路由直接打开的菜单
                if (dist === 'to') {
                    let res = getNodes(this.rawData, item, _getNodesObj, 0);
                    if (!res) {
                        console.error('没有找到对应的路由菜单！')
                        return false //有的路由没在菜单中,什么都不要做,否则报错
                    }
                    if (_getNodesObj.length > 1) {
                        let obj = _getNodesObj[_getNodesObj.length - 2];
                        this.menuData = obj.subMenu;
                        this.parentState.title = obj.title;
                        this.parentState.state = obj.state;
                        // 按拼音首字母排序
                        if (this.sort) {
                            this.sortArr(this.menuData, 'title')
                        }
                    }else{
                        this.menuData = this.rawData;
                        this.parentState.title = null;
                        this.parentState.state = null;
                    }
                    this.currentState = _getNodesObj[_getNodesObj.length - 1].state;
                    this.toggleVal = (_getNodesObj[_getNodesObj.length - 1].open < 1); // 根据传入的open值决定侧栏是否展开

                    // 缓存当前父级状态
                    this.curParent = this.parentState.state
                }
                //点击返回上一级打开的菜单
                if (dist === 'back') {
                    //执行动画
                    this.cont1 = 'cont1 c1-left';
                    this.cont2 = 'cont2 show c2-left';

                    getNodes(this.rawData, this.parentState.state, _getNodesObj, 0);
                    if (_getNodesObj.length > 1) { //如果不是第一层就获取前一层级的数据
                        let obj = _getNodesObj[_getNodesObj.length - 2];
                        this.menuData = obj.subMenu;
                        this.parentState.title = obj.title;
                        this.parentState.state = obj.state;
                    }else{ //如果是第一层就直接调用原始数据
                        this.menuData = this.rawData;
                        this.parentState.title = null;
                        this.parentState.state = null;
                    }
                    /*this.currentState = _getNodesObj[_getNodesObj.length - 1].state;*/
                }
                this.searchText = ''
                return false;
            },
            // 按首字母排序
            sortArr(arr, keyword) {
                arr.sort(function(param1, param2) {
                        // console.log(1111, param1.sort)
                        // console.log(2222, param2.sort)
                        // console.log(3333, param1[keyword])
                        /*if(param1.sort) param1[keyword] = param1.sort
                       if(param2.sort) param2[keyword] = param2.sort
                       console.log(2, param1[keyword], param2[keyword])*/
                        // data上有sort属性就以次属性为主
                        return ((param1.sort && param1.sort.toString()) || param1[keyword])
                            .localeCompare((param2.sort && param2.sort.toString()) || param2[keyword]);
                    }
                )
            },
            //打开连接
            linkTo(v) {
                if (this.$store.getters.stopGoBack) { //路由已被锁定状态
                    this.$confirm('当前页面还有未保存的内容，确认要离开吗？', '提示', {
                        type: 'warning'
                    }).then(() => { //点击确认按钮后
                        this.searchText = ''
                        this.$store.commit('SET_URL', null);
                        this.$router.replace({
                            path: v
                        });
                    }).catch(() => { //点击取消按钮后
                        return false
                    })
                    // this.$eventHub.$emit('closeThis', v); //提交关闭指令给关闭窗口的组件
                }else{
                    this.searchText = ''
                    this.$router.replace({
                        path: v
                    });
                }
            },
            // 显示搜索框并获取焦点
            showInput() {
                this.showSearch = true
                this.$nextTick(function() {
                    this.$refs.searchInput.focus()
                })
            },
            // 隐藏搜索框
            hideInput() {
                this.showSearch = false
            },
            resetInput() {
                this.searchText = ''
                this.hideInput()
            }
        }
    };
</script>
